package ca.llsutherland.squash.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ca.llsutherland.squash.exceptions.ValidationException;

public class StringUtils {

    
    public static boolean containsInvalidCharacters(String string) throws ValidationException {
        return !containsOnlyValidCharacters(string);
    }
    
    public static boolean containsOnlyValidCharacters(String string) throws ValidationException {
        return containsValidCharacters(string);
    }
    
     public static String addSingleQuotes(String string) {
        return "'" + string.replaceAll("'", "''") + "'";
    }
    
    private static boolean containsValidCharacters(String string) throws ValidationException {
        String trimmedString = string.trim();
        if(trimmedString.length() == 0){
            throw new ValidationException(ErrorConstants.INVALID_CHARACTER_IN_STRING_ERROR);
        }
        Pattern characterPattern = Pattern.compile("^[a-zA-Z_0-9_\\s]*");
        Matcher characterMatcher = characterPattern.matcher(trimmedString);
        return characterMatcher.matches();
    }

    public static boolean isValidFormattedPhoneNumber(String phoneNumber) {
        /* Phone Number formats: (nnn)nnn-nnnn; nnnnnnnnnn; nnn-nnn-nnnn 
            ^\\(? : May start with an option "(" . 
            (\\d{3}): Followed by 3 digits. 
            \\)? : May have an optional ")" 
            [- ]? : May have an optional "-" after the first 3 digits or after optional ) character. 
            (\\d{3}) : Followed by 3 digits. 
             [- ]? : May have another optional "-" after numeric digits. 
             (\\d{4})$ : ends with four digits. 
         
                 Examples: Matches following <a href="http://mylife.com">phone numbers</a>: 
                 (123)456-7890, 123-456-7890, 1234567890, (123)-456-7890 
         
        */  
        //Initialize reg ex for phone number.   
        CharSequence inputStr = phoneNumber;  
        Pattern pattern = Pattern.compile("^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$");  
        Matcher matcher = pattern.matcher(inputStr);
        if(matcher.matches()){  
            return true;  
        }  
        return false; 
    }

    public static boolean isBlankString(String string) {
        return (string == null || string.trim().length() == 0);
    }
}
